ClientGui = Class.create({
  initialize: function () { 
    this._viewsElement = $('views');
    this._scenesViewScenesList = $('scenesView-scenesList');
    this._meViewTabsControl = new S2.UI.Tabs('meView-tabs');
    this._othersViewTabControl = new S2.UI.Tabs('othersView-tabs');
    this._marketViewTabControl = new S2.UI.Tabs('marketView-tabs');
    
    this._sceneContainerClickListener = this._onSceneContainerClick.bindAsEventListener(this);
    this._taskContainerClickListener = this._onTaskContainerClick.bindAsEventListener(this);
    this._inventoryItemGridCellClickListener = this._onInventoryItemGridCellClick.bindAsEventListener(this);
    this._popupDialogWindowClickListener = this._onPopupDialogWindowClick.bindAsEventListener(this);
    
    this._othersViewNearbyUserContainerClickListener = this._onOthersViewNearbyUserContainerClick.bindAsEventListener(this);
    this._othersViewFriendRequestContainerClickListener = this._onOthersViewFriendRequestContainerClick.bindAsEventListener(this);
    this._othersViewFriendContainerClickListener = this._onOthersViewFriendContainerClick.bindAsEventListener(this);
    
    this._sceneCache = new Hash();
    this._inventoryItemCache = new Hash();
    this._userCache = new Hash();
    this._viewH = 0;
    this._viewV = 0;
    this._loading = 0;
    this._currentSceneId = null;
    this._mockedPosition = null;
    this._viewIds = {
      "1.0":"meView",
      "0.1":"othersView",
      "1.1":"scenesView",
      "2.1":"hereView",
      "1.2":"marketView"
    };
  },
  loadScenes: function () {
	  this._currentSceneId = null;
	  this.setSideBarEnabled('scenesView-hereSideBar', false);
	  this._setSideBarTitle('scenesView-hereSideBar', 'Here');
	  var _this = this;
	  this._startLoading();
	  this._removeScenes();
	  this._getGeoLocation(function (position) {
	    getCriminalSoulsApi().apiRequest('/scenes/findNearbyScenes', { 'lat': position.coords.latitude, 'lng': position.coords.longitude }, 
	      function (response) {
	        var scenes = response.responseJSON.scenes;
	        for (var i = 0, l = scenes.length; i < l; i++) {
	          var scene = scenes[i];
	          _this._addScene(scene);
	        }
	      
	        _this._stopLoading();
	      }
	    );
	  });
  },
  loadInventory: function () {
	  var _this = this;
	  this._inventoryItemCache = new Hash();
    getCriminalSoulsApi().apiRequest('/users/getInventory', null, 
	    function (response) {
		    $('meView-money').update(_this._formatMoney(response.responseJSON.money));
		    var inventoryItemsGrid = $('meView-inventoryItemsGrid');
		    var cells = inventoryItemsGrid.select('.listSectionGridCell');
		    for (var i = cells.length - 1; i >= 0; i--) {
		      cells[i].purge();
		      cells[i].remove();
		    }
		
		    var inventoryItems = response.responseJSON.inventoryItems;
		    for (var i = 0, l = inventoryItems.length; i < l; i++) {
		      var gridCell = new Element("div", {className: "listSectionGridCell listSectionGridCellClickable" });
		      var gridCellInputId = new Element("input", {type: "hidden", name: "inventoryItemId", value: inventoryItems[i].id }); 
		      var gridCellImage = new Element("img", { className: "listSectionGridCellImage", src: 'css/images/32x32/' + inventoryItems[i].item.icon + '.png', label: inventoryItems[i].item.name});
		      var gridCellLabelContainer = new Element("div", {className: "listSectionGridCellLabelContainer" });
		      var gridCellLabelInnerContainer = new Element("div", {className: "listSectionGridCellLabelInnerContainer" });
		      var gridCellLabel = new Element("div", {className: "listSectionGridCellLabel" }).update(inventoryItems[i].count);
		      gridCell.appendChild(gridCellImage);
		      gridCell.appendChild(gridCellInputId);
		      gridCellLabelInnerContainer.appendChild(gridCellLabel);
		      gridCellLabelContainer.appendChild(gridCellLabelInnerContainer);
		      gridCell.appendChild(gridCellLabelContainer);
		      inventoryItemsGrid.appendChild(gridCell);
		   
 		      Event.observe(gridCell, "click", _this._inventoryItemGridCellClickListener);
 		      _this._inventoryItemCache.set(inventoryItems[i].id, {
 			      inventoryId: inventoryItems[i].inventoryId,
 			      count: inventoryItems[i].count,
 			      itemId: inventoryItems[i].item.id,
 			      itemName: inventoryItems[i].item.name,
 			      itemIcon: inventoryItems[i].item.icon
 		      });
		    }
	    }
    );
  },
  loadStashedItems: function () {
	  var _this = this;
    getCriminalSoulsApi().apiRequest('/items/listStashedItems', null, 
	    function (response) {
		    var stashedItemsGrid = $('meView-inventoryStashedItemsGrid');
		    var cells = stashedItemsGrid.select('.listSectionGridCell');
		    for (var i = cells.length - 1; i >= 0; i--) {
		      cells[i].purge();
		      cells[i].remove();
		    }
		
		    var stashedItems = response.responseJSON.stashedItems;
		    for (var i = 0, l = stashedItems.length; i < l; i++) {
    		  var gridCell = new Element("div", {className: "listSectionGridCell listSectionGridCellClickable" });
    		  var gridCellInputId = new Element("input", {type: "hidden", name: "stashedItemId", value: stashedItems[i].id }); 
    		  var gridCellImage = new Element("img", { className: "listSectionGridCellImage", src: 'css/images/32x32/' + stashedItems[i].item.icon + '.png', label: stashedItems[i].item.name});
     	    var gridCellLabelContainer = new Element("div", {className: "listSectionGridCellLabelContainer" });
    		  var gridCellLabelInnerContainer = new Element("div", {className: "listSectionGridCellLabelInnerContainer" });
    		  var gridCellLabel = new Element("div", {className: "listSectionGridCellLabel" }).update(stashedItems[i].count);
    		  gridCell.appendChild(gridCellImage);
    		  gridCell.appendChild(gridCellInputId);
    		  gridCellLabelInnerContainer.appendChild(gridCellLabel);
    		  gridCellLabelContainer.appendChild(gridCellLabelInnerContainer);
    		  gridCell.appendChild(gridCellLabelContainer);
    		  stashedItemsGrid.appendChild(gridCell);
		    }
	    }
    );
  },
  loadNearbyUsers: function () {
    var _this = this;
    this._startLoading();
    this._getGeoLocation(function (position) {
      getCriminalSoulsApi().apiRequest('/users/findNearbyUsers', { 'lat': position.coords.latitude, 'lng': position.coords.longitude }, 
        function (response) {
	        var currentLocation = new LatLon(position.coords.latitude, position.coords.longitude);
	        var users = response.responseJSON.users;
	        var nearbyList = $('othersView-nearbyList');
	        
	        var userContainers = nearbyList.select('.listSectionListItemContainer');
	        for (var i = userContainers.length - 1; i >= 0; i--) {
	          userContainers[i].purge();
	          userContainers[i].remove();
	        }
	     
	        for (var i = 0, l = users.length; i < l; i++) {
	          var user = users[i];
	          var distance;
	        
	          if (user.location) {
	            var userLocation = new LatLon(user.location.latitude, user.location.longitude);
	            distance = userLocation.distanceTo(currentLocation) * 1000;
	          } else {
	            distance = '';
	          }
	      
	          var userContainer = new Element("div", {className: "listSectionListItemContainer listSectionListDualItemContainer"});
	          var userId = new Element("input", {type: "hidden", value: user.id, name: "userId"});
	          var userName = new Element("a", {className: "listSectionListItem listSectionListDualItemFirst", href:"javascript:void(null)"}).update(user.firstName + ' ' + user.lastName);
	          var userDistance = new Element("div", {className: "listSectionListItem listSectionListDualItemSecond", href:"javascript:void(null)"}).update(_this._formatDistance(distance));

	          Event.observe(userContainer, "click", _this._othersViewNearbyUserContainerClickListener);
	      	
	          userContainer.appendChild(userId);
	          userContainer.appendChild(userName);
	          userContainer.appendChild(userDistance);
	      	
	          nearbyList.appendChild(userContainer);
	        
	          _this._cacheUser(user);
	        }
	      
	        _this._stopLoading();
	      }
      );
    });  
  },
  loadConfirmedFriends: function () {
	  var _this = this;
    this._startLoading();
	  this._getGeoLocation(function (position) {
      getCriminalSoulsApi().apiRequest('/users/listConfirmedFriends', null, 
		    function (response) {
	        var currentLocation = new LatLon(position.coords.latitude, position.coords.longitude);
		      var friends = response.responseJSON.friends;
		      var friendsList = $('othersView-friendsList');
		        
		      var friendContainers = friendsList.select('.listSectionListItemContainer');
		      for (var i = friendContainers.length - 1; i >= 0; i--) {
			      friendContainers[i].purge();
			      friendContainers[i].remove();
		      }
		   
	        for (var i = 0, l = friends.length; i < l; i++) {
  			    var friend = friends[i];		
  			  
  	        var distance;
  	        
  	        if (friend.location) {
  		        var friendLocation = new LatLon(friend.location.latitude, friend.location.longitude);
  		        distance = friendLocation.distanceTo(currentLocation) * 1000;
  	        } else {
  	          distance = '';
  	        }
  			  
  			    var friendContainer = new Element("div", {className: "listSectionListItemContainer listSectionListDualItemContainer"});
  		      var friendId = new Element("input", {type: "hidden", value: friend.id, name: "friendId"});
  		      var friendName = new Element("a", {className: "listSectionListItem listSectionListDualItemFirst", href:"javascript:void(null)"}).update(friend.firstName + ' ' + friend.lastName);
  		      var friendDistance = new Element("div", {className: "listSectionListItem listSectionListDualItemSecond", href:"javascript:void(null)"}).update(_this._formatDistance(distance));

            Event.observe(friendContainer, "click", _this._othersViewFriendContainerClickListener);

  		      friendContainer.appendChild(friendId);
  		      friendContainer.appendChild(friendName);
  		      friendContainer.appendChild(friendDistance);
  		      	
  		      friendsList.appendChild(friendContainer);
  		    
  	        _this._cacheUser(friend);
	        }
			
		      _this._stopLoading();
	      }
	    );
	  });
  },
  loadUnconfirmedFriends: function () {
    var _this = this;
    this._startLoading();

	  getCriminalSoulsApi().apiRequest('/users/listUnconfirmedFriends', null, 
      function (response) {
	      var friends = response.responseJSON.friends;
			
	      var friendsList = $('othersView-friendRequestsList');
        var friendContainers = friendsList.select('.listSectionListItemContainer');
	      for (var i = friendContainers.length - 1; i >= 0; i--) {
	        friendContainers[i].purge();
	        friendContainers[i].remove();
	      }
		   
  	    for (var i = 0, l = friends.length; i < l; i++) {
          var friend = friends[i];		
  		  
          var friendContainer = new Element("div", {className: "listSectionListItemContainer listSectionListDualItemContainer"});
          var friendId = new Element("input", {type: "hidden", value: friend.id, name: "friendId"});
          var friendName = new Element("a", {className: "listSectionListItem listSectionListDualItemFirst", href:"javascript:void(null)"}).update(friend.firstName + ' ' + friend.lastName);
          // TODO: City
          var friendCity = new Element("div", {className: "listSectionListItem listSectionListDualItemSecond", href:"javascript:void(null)"}).update('Todo: City');

          Event.observe(friendContainer, "click", _this._othersViewFriendRequestContainerClickListener);

          friendContainer.appendChild(friendId);
          friendContainer.appendChild(friendName);
    	    friendContainer.appendChild(friendCity);
    		      	
    	    friendsList.appendChild(friendContainer);
    	    
          _this._cacheUser(friend);
    	  }
    	    
    	  _this._stopLoading();
      }
	  );
  },
  performGeneralTask: function (generalTaskLevelId) {
    var _this = this;
	  getCriminalSoulsApi().apiRequest('/tasks/performGeneralTask', {"generalTaskLevelId": generalTaskLevelId}, 
	    function (response) {
		    var toastMessage;
		    if (response.responseJSON.taskRewards.money > 0) {
	        toastMessage = '<li>' + _this._formatMoney(response.responseJSON.taskRewards.money) + '</li>';
	      }
	    
	      if (response.responseJSON.taskRewards.items.length > 0) {
	        for (var i = 0, l = response.responseJSON.taskRewards.items.length; i < l; i++) {
    	      var item = response.responseJSON.taskRewards.items[i];
	          toastMessage += '<li>' + item.count + ' x ' + item.item.name + '</li>';
	        }
	      }
	   
        _this.showToast("Your reward was: <ul>" + toastMessage + '</ul>');
	      _this.loadInventory();
  	  }
	  );  
  },
  addFriend: function (friendId) {
    var _this = this;
	  getCriminalSoulsApi().apiRequest('/users/addFriend', { "friendId": friendId }, 
	    function (response) {
        _this.showToast("Sent friend request");
  	  }
	  );  
  },
  setView: function (h, v) {
	  var topOffset = document.viewport.getHeight() * v;	
  	var leftOffset = document.viewport.getWidth() * h;
  	this._viewsElement.setStyle({
  	  top: '-' + topOffset + 'px',
  	  left: '-' + leftOffset + 'px'
  	});
  	this._viewH = h;
  	this._viewV = v;
  },
  moveToView: function (h, v) {
    var topOffset = document.viewport.getHeight() * v;	
	  var leftOffset = document.viewport.getWidth() * h;
	  this._viewsElement.morph('top:-' + topOffset + 'px;left:-' + leftOffset + 'px', { duration: 0.5 });
  	this._viewH = h;
  	this._viewV = v;
  },
  showToast: function (message) {
    var toastContainer = new Element("div", {className: "toastContainer"});
    var toastInnerContainer = new Element("div", {className: "toastInnerContainer"});
    var toastMessage = new Element("div", {className: "toastMessage"}).update(message);
    toastInnerContainer.appendChild(toastMessage);
    toastContainer.appendChild(toastInnerContainer);	
    document.body.appendChild(toastContainer);
    
    Element.fade.delay(5, toastContainer);
  },
  openPopupDialog: function (html, top, left, width, height) {
	  var popupContainer = new Element("div", {id: "popupContainer"});
	  var popupInnerContainer = new Element("div", {id: "popupInnerContainer"});
	  var popupContents = new Element("div", {id: "popupContents"}).update(html);
	  popupInnerContainer.appendChild(popupContents);
	  popupContainer.appendChild(popupInnerContainer);	
	  document.body.appendChild(popupContainer);
	  popupContainer.setStyle({
	    top: top + 'px',
	    left: left + 'px',
	    width: width + 'px',
	    height: height + 'px'
	  });
	  Event.observe(window, "mousedown", this._popupDialogWindowClickListener);
  },
  closePopupDialog: function () {
	  $("popupContainer").remove();  
	  Event.stopObserving(window, "mousedown", this._popupDialogWindowClickListener);
  },
  openModalDialog: function (title, html, width, height) {
	  this._addGlassPane();
    var modalDialogContainer = new Element("div", {id: "modalDialogContainer"});
	  var modalDialogInnerContainer = new Element("div", {id: "modalDialogInnerContainer"});
  	var modalDialog = new Element("div", {id: "modalDialog"})
  	var modalDialogTitle = new Element("div", {id: "modalDialogTitle"}).update(title);
  	var modalDialogContents = new Element("div", {id: "modalDialogContents"}).update(html);
	
  	modalDialog.appendChild(modalDialogTitle);
  	modalDialog.appendChild(modalDialogContents);
  	
  	modalDialogInnerContainer.appendChild(modalDialog);
  	modalDialogContainer.appendChild(modalDialogInnerContainer);	
  	document.body.appendChild(modalDialogContainer);
  	modalDialog.setStyle({
  	  width: width + 'px',
  	  height: height + 'px'
  	});  
  },
  closeModalDialog: function () {
  	this._removeGlassPane();  
  	$('modalDialogContainer').remove();
  },
  setSideBarEnabled: function (id, enabled) {
  	var sideBar = $(id);
  	if (sideBar.hasClassName('sideBarDisabled')) {
	    if (enabled) {
		    var onClick = sideBar.getAttribute("_onclick");
    	  if (onClick) {
    	    sideBar.removeAttribute("_onclick");
    	    sideBar.setAttribute("onclick", onClick);
    	  }	
	      sideBar.removeClassName('sideBarDisabled');  
	    }	
  	} else {
        if (!enabled) {
          var onClick = sideBar.getAttribute("onclick");
      	if (onClick) {
      	  sideBar.removeAttribute("onclick");
      	  sideBar.setAttribute("_onclick", onClick);
      	}	
      	
      	sideBar.addClassName('sideBarDisabled');
  	  }	
  	}
  },
  setMockedPosition: function (position) {
    this._mockedPosition = position;
  },
  _cacheUser: function (user) {
    var cachedUser = this._userCache.get(user.id);
    var entry = Object.extend({
      firstName: user.firstName,
      lastName: user.lastName
    }, cachedUser||{});
    
    if (user.location) {
      entry.locationLatitude = user.location.latitude;
      entry.locationLongitude = user.location.longitude;
    }
    
    if (!Object.isUndefined(user.isFriend)) {
      entry.isFriend = user.isFriend;
    }

    if (!Object.isUndefined(user.isFriend)) {
      entry.isFriendshipRequested = user.isFriendshipRequested;
    }
    
    this._userCache.set(user.id, entry);
  },
  _startLoading: function () {
    if (this._loading == 0) {
      this._loadingPane = new Element("div", {id: "loadingPane"});
  	  document.body.appendChild(this._loadingPane);
    }
    this._loading++; 
  },
  _stopLoading: function () {
    this._loading--;
    if (this._loading >= 0) {
      this._loadingPane.remove();
      this._loading = 0;
    }
  },
  _addGlassPane: function () {
    this._glassPane = new Element("div", {id: "glassPane"});
  	document.body.appendChild(this._glassPane);
  },
  _removeGlassPane: function () {
    this._glassPane.remove();
  },
  _getCurrentViewElement: function () {
	  return $(this._viewIds[this._viewH + '.' + this._viewV]);
  },
  _getGeoLocation: function (callback) {
    if (this._mockedPosition) {
      callback(this._mockedPosition);
    } else {
      navigator.geolocation.getCurrentPosition(function(position) {
        callback(position);
      });
    }
  },
  _getCurrentSceneId: function () {
    return this._currentSceneId;  
  },
  _setSideBarTitle: function (id, title) {
    var sideBar = $(id);
    var sideBarTitle = sideBar.down('.sideBarTitle');
    sideBarTitle.update(title);	
  },
  _removeScenes: function () {
    var sceneContainers = this._scenesViewScenesList.select('.listSectionListItemContainer');
    for (var i = sceneContainers.length - 1; i >= 0; i--) {
      sceneContainers[i].purge();
      sceneContainers[i].remove();
    }
  },
  _addScene: function (scene) {
    var sceneContainer = new Element("div", {className: "listSectionListItemContainer listSectionListDualItemContainer"});
    var sceneId = new Element("input", {type: "hidden", value: scene.id, name: "sceneId"});
    var sceneName = new Element("a", {className: "listSectionListItem listSectionListDualItemFirst", href:"javascript:void(null)"}).update(scene.name);
    var sceneDistance = new Element("div", {className: "listSectionListItem listSectionListDualItemSecond"}).update(this._formatDistance(scene.distance));
	
    Event.observe(sceneContainer, "click", this._sceneContainerClickListener);
	
    sceneContainer.appendChild(sceneId);
    sceneContainer.appendChild(sceneName);
    sceneContainer.appendChild(sceneDistance);
	
    this._scenesViewScenesList.appendChild(sceneContainer);
	
    this._sceneCache.set(scene.id, {
  	  name: scene.name,
  	  lng: scene.lng,
  	  lat: scene.lat,
  	  categoryId: scene.category.id,
  	  categoryName: scene.category.name
  	});
  },
  _viewScene: function (sceneId) {
    var _this = this;
    this._startLoading();
    getCriminalSoulsApi().apiRequest('/tasks/findTasks', { 'sceneId': sceneId }, 
      function (response) {
        var sceneData = _this._sceneCache.get(sceneId);
		
        _this._currentSceneId = response.responseJSON.sceneId;
        _this.setSideBarEnabled('scenesView-hereSideBar', _this._currentSceneId > 0);
        _this._setSideBarTitle('scenesView-hereSideBar', 'Here (' + sceneData.name + ')');
        var tasksList = $('hereView-tasksList');
        
        var taskContainers = tasksList.select('.listSectionListItemContainer');
        for (var i = taskContainers.length - 1; i >= 0; i--) {
          taskContainers[i].purge();
          taskContainers[i].remove();
        }
		
        var generalTaskLevels = response.responseJSON.generalTaskLevels;
        var customTasks = response.responseJSON.customTasks;
        
        $('hereView-name').update(sceneData.name);
        $('hereView-category').update(sceneData.categoryName);
        
        for (var i = 0, l = generalTaskLevels.length; i < l; i++) {
          var generalTaskLevel = generalTaskLevels[i];
          
          var taskContainer = new Element("div", {className: "listSectionListItemContainer listSectionListBasicItemContainer"});
          var taskId = new Element("input", {type: "hidden", value: generalTaskLevel.id, name: "generalTaskLevelId"});
          var taskName = new Element("a", {className: "listSectionListItem listSectionListBasicItem", href:"javascript:void(null)"}).update(generalTaskLevel.name);
      	  
          Event.observe(taskContainer, "click", _this._taskContainerClickListener);
      	
          taskContainer.appendChild(taskId);
      	  taskContainer.appendChild(taskName);
      	
      	  tasksList.appendChild(taskContainer);
        }
        
        getCriminalSoulsApi().apiRequest('/items/listStashedItems', { 'sceneId': sceneId }, 
          function (response) {
          	var stashedItemSection = $('hereView-stashedItemsSection');
          	var stashedItems = response.responseJSON.stashedItems;
          	var stashedItemsList = $('hereView-stashedItemsList');
      		
          	var itemContainers = stashedItemsList.select('.listSectionListItemContainer');
          	for (var i = itemContainers.length - 1; i >= 0; i--) {
          	  itemContainers[i].purge();
          	  itemContainers[i].remove();
          	}
    		
          	stashedItemSection.setStyle({
          	  'display': stashedItems.length > 0 ? 'block' : 'none'
          	});
    		
        	  for (var i = 0, l = stashedItems.length; i < l; i++) {
	            var stashedItem = stashedItems[i];
	          
	            var itemContainer = new Element("div", {className: "listSectionListItemContainer listSectionListBasicItemContainer"});
	            var itemName = new Element("div", {className: "listSectionListItem listSectionListBasicItem", href:"javascript:void(null)"}).update(stashedItem.count + ' x ' + stashedItem.item.name);
	      	  
	            itemContainer.appendChild(itemName);
	      	
	            stashedItemsList.appendChild(itemContainer);
	          }
          }
        );
        
        _this.moveToView(2, 1);
        _this._stopLoading();
	    }
    );
  },
  _stashInventoryItems: function (inventoryItemId, count) {
    var _this = this;
    getCriminalSoulsApi().apiRequest('/items/stashItems', {"inventoryItemId": inventoryItemId, "sceneId": this._getCurrentSceneId(), "count": count }, 
      function (response) {
        _this.loadInventory();
        _this.loadStashedItems();
  	  }
    ); 
  },
  _onSceneContainerClick: function (event) {
    var sceneContainer = Event.element(event);  
    if (!sceneContainer.hasClassName("listSectionListItemContainer"))
      sceneContainer = sceneContainer.up(".listSectionListItemContainer");
    this._viewScene(sceneContainer.down('input[name="sceneId"]').value);
  },
  _onTaskContainerClick: function (event) {
    var taskContainer = Event.element(event);  
    if (!taskContainer.hasClassName("listSectionListItemContainer"))
      taskContainer = taskContainer.up(".listSectionListItemContainer");
    this.performGeneralTask(taskContainer.down('input[name="generalTaskLevelId"]').value);
  },
  _onInventoryItemGridCellClick: function (event) {
    var listSectionGridCell = Event.element(event);  
    if (!listSectionGridCell.hasClassName("listSectionGridCell"))
      listSectionGridCell = listSectionGridCell.up(".listSectionGridCell");
	
    var inventoryItemId = listSectionGridCell.down('input[name="inventoryItemId"]').value;
    var cachedItem = this._inventoryItemCache.get(inventoryItemId);
    var gridOffset = Element.cumulativeOffset(listSectionGridCell);
	
    var html = 
  	  '<div class="inventoryItemPopupItemName">' + cachedItem.itemName + '</div>' + 
  	  '<div class="inventoryItemPopupItemCount">' + cachedItem.count + ' pc.' + '</div>' + 
  	  '<div class="inventoryItemPopupItemIcon"><img src="' + 'css/images/32x32/' + cachedItem.itemIcon + '.png' + '"/></div>' + 
  	  '<div class="inventoryItemPopupButtons">' + 
  	    '<button id="meView-inventoryItemStashButton"' + (this._getCurrentSceneId() ? '' : ' disabled="disabled"') + '>Stash</button>' +
  	    '<button id="meView-inventoryItemSellButton">Sell</button>' +
  	    '<button id="meView-inventoryItemDropButton">Drop</button>' +
  	  '</div>';
	
    this.openPopupDialog(html, gridOffset.top + 3, gridOffset.left + 11, 200, 90);
	
    var _this = this;
    Event.observe($('meView-inventoryItemStashButton'), "click", function (event) {
      var sceneData = _this._sceneCache.get(_this._getCurrentSceneId());
      var itemName = cachedItem.itemName.truncate(15);
      var sceneName = sceneData.name.truncate(20); 
      var itemCount = cachedItem.count;
	  
      var html = 
  	    '<div id="meView-inventoryItemStashText">choose number of \'' + itemName + '\' items to be stashed into \'' + sceneName + '\' scene:</div>' +
    		'<div id="meView-inventoryItemStashCountSliderContainer">' + 
    	  '  <div id="meView-inventoryItemStashCountSlider"></div>' +
    	  '  <input type="text" id="meView-inventoryItemStashCountSliderInput" value="' + itemCount + '"/>' + 
    	  '</div>' +
    	  '<div class="modalDialogButtons" id="meView-inventoryItemStashButtons">' + 
    	  '  <button id="meView-inventoryItemStashDialogStashButton">Stash</button>' +
    	  '  <button id="meView-inventoryItemStashDialogCancelButton">Cancel</button>' +
    	  '</div>'
  	      
  	  _this.openModalDialog('Stash items', html, 350, 120);	
      var countSlider = new S2.UI.Slider($('meView-inventoryItemStashCountSlider'), {
        value: { min: 0, max: itemCount, initial: itemCount, step: 1 },
        onSlide: function (value) {
          $('meView-inventoryItemStashCountSliderInput').value = value;
        }
      });
        
      Event.observe($('meView-inventoryItemStashCountSliderInput'), "keyup", function (event) {
        var input = Event.element(event);
        var intValue = parseInt(input.value);
        if (isNaN(intValue)) {
          intValue = 0;
        } else {
          if (intValue > itemCount)
            intValue = itemCount;
        }
          
        countSlider.setValue(intValue);
      });
        
      Event.observe($('meView-inventoryItemStashDialogStashButton'), 'click', function (event) {
        var itemCount = $('meView-inventoryItemStashCountSliderInput').value; 
        _this._stashInventoryItems(inventoryItemId, itemCount);
        _this.closeModalDialog();
        _this.closePopupDialog();
      });
        
      Event.observe($('meView-inventoryItemStashDialogCancelButton'), 'click', function (event) {
        _this.closeModalDialog();  
      });
  	});
	
  	Event.observe($('meView-inventoryItemSellButton'), "click", function (event) {
  	  // TODO: Sell button
  	  alert('TODO: Sell button');
  	});

	  Event.observe($('meView-inventoryItemDropButton'), "click", function (event) {
  	  // TODO: Drop button
  	  alert('TODO: Drop button');
	  });
  },
  _onOthersViewNearbyUserContainerClick: function (event) {
	  var userContainer = Event.element(event);  
	  if (!userContainer.hasClassName("listSectionListItemContainer"))
		  userContainer = userContainer.up(".listSectionListItemContainer");
	  
	  var userId = userContainer.down('input[name="userId"]').value
	  var offset = Element.cumulativeOffset(userContainer);
	  var cachedUser = this._userCache.get(userId);
	
	  // TODO: City
	  var html = 
  	  '<div class="userPopupUserName">' + cachedUser.firstName + ' ' + cachedUser.lastName + '</div>' + 
  	  '<div class="userPopupItemIcon"><img src="' + 'css/images/32x32/unknownuser.png' + '"/></div>' + 
  	  '<div class="userPopupUserCity">' + 'Todo: city' + '</div>' +
  	  '<div class="userPopupButtons">' + 
  	    '<button id="othersView-addAsFriendButton"' + (cachedUser.isFriendshipRequested ? ' disabled="disabled"' : '') + '>Add as friend</button>' +
  	    '<button id="othersView-sendMessageButton">Send message</button>' +
  	  '</div>';
	
	  this.openPopupDialog(html, offset.top + 3, offset.left + 4, 250, 90);
	
	  var _this = this;
	  Event.observe($('othersView-addAsFriendButton'), "click", function (event) {
      _this.closePopupDialog();
      _this.addFriend(userId);
	  });
    Event.observe($('othersView-sendMessageButton'), "click", function (event) {
      alert('todo');
    });
  },
  _onOthersViewFriendRequestContainerClick: function (event) {
    var userContainer = Event.element(event);  
    if (!userContainer.hasClassName("listSectionListItemContainer"))
      userContainer = userContainer.up(".listSectionListItemContainer");
    
    var userId = userContainer.down('input[name="friendId"]').value
    var offset = Element.cumulativeOffset(userContainer);
    var cachedUser = this._userCache.get(userId);
  
    // TODO: City
    var html = 
      '<div class="userPopupUserName">' + cachedUser.firstName + ' ' + cachedUser.lastName + '</div>' + 
      '<div class="userPopupItemIcon"><img src="' + 'css/images/32x32/unknownuser.png' + '"/></div>' + 
      '<div class="userPopupUserCity">' + 'Todo: city' + '</div>' +
      '<div class="userPopupButtons">' + 
        '<button id="othersView-confirmFriendshipButton">Confirm</button>' +
        '<button id="othersView-sendMessageButton">Send message</button>' +
      '</div>';
  
    this.openPopupDialog(html, offset.top + 3, offset.left + 4, 250, 90);
  
    var _this = this;
    Event.observe($('othersView-confirmFriendshipButton'), "click", function (event) {
      _this.closePopupDialog();
      alert('todo');
    });
    Event.observe($('othersView-sendMessageButton'), "click", function (event) {
      alert('todo');
    });
  },
  _onOthersViewFriendContainerClick: function (event) {
    var userContainer = Event.element(event);  
    if (!userContainer.hasClassName("listSectionListItemContainer"))
      userContainer = userContainer.up(".listSectionListItemContainer");
    
    var userId = userContainer.down('input[name="friendId"]').value
    var offset = Element.cumulativeOffset(userContainer);
    var cachedUser = this._userCache.get(userId);
  
    // TODO: City
    var html = 
      '<div class="userPopupUserName">' + cachedUser.firstName + ' ' + cachedUser.lastName + '</div>' + 
      '<div class="userPopupItemIcon"><img src="' + 'css/images/32x32/unknownuser.png' + '"/></div>' + 
      '<div class="userPopupUserCity">' + 'Todo: city' + '</div>' +
      '<div class="userPopupButtons">' + 
        '<button id="othersView-sendMessageButton">Send message</button>' +
      '</div>';
  
    this.openPopupDialog(html, offset.top + 3, offset.left + 4, 250, 90);
  
    var _this = this;
    Event.observe($('othersView-sendMessageButton'), "click", function (event) {
      alert('todo');
    });
  },
  _onPopupDialogWindowClick: function (event) {
	  if (!$('glassPane')) {
	    var currentElement = Event.element(event);  
	    if (currentElement.id != 'popupContainer') {
	      if ((!currentElement.up('#popupContainer')))
		      this.closePopupDialog();
	    }
	  }
  },
  _formatMoney: function (money) {
	  return money.toFixed(2) + ' IBCS';
  },
  _formatDistance: function (distance) {
	  if ((distance)||(distance === 0)) {
      if (distance > 1000)
        return '> ' + Math.round(distance / 1000)  + ' km';
      else
    	  return Math.round(distance) + ' m';
	  } else {
	    return '';
	  }
  }
});